import {AfterViewInit, Component, OnInit, ViewEncapsulation} from '@angular/core';
import {Router} from '@angular/router';
import {PAGES_MENU} from '../menu';
import {MenuService} from '../../lib/service/admin/menu.service';

@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.scss'],
})
export class MenuComponent implements OnInit, AfterViewInit {

  public menus = [[]];
  public hideList = [
    {'parent': 'list', 'node': 'activity_add'},
    {'parent': 'list', 'node': 'activity_edit'},
    {'parent': 'list', 'node': 'activity_change_status'},
    {'parent': 'list', 'node': 'activity_delete'},
    {'parent': 'list', 'node': 'invitation_add'},
    {'parent': 'list', 'node': 'add_task'},
    {'parent': 'hot', 'node': 'add_hot'},
    {'parent': 'user', 'node': 'add_user'},
    {'parent': 'hot', 'node': 'edit_hot'},
    {'parent': 'hot', 'node': 'delete_hot'},
    {'parent': 'list', 'node': 'edit_task'},
    {'parent': 'list', 'node': 'delete_task'},
    {'parent': 'list', 'node': 'edit_taskmanage'},
    {'parent': 'list', 'node': 'add_robot'},
    {'parent': 'list', 'node': 'delete_robot'},
    {'parent': 'list', 'node': 'add_integral'},
    {'parent': 'list1', 'node': 'delete_integral'},
    {'parent': 'list', 'node': 'add_discovery_activity'},
    {'parent': 'list', 'node': 'add_discovery_category'},
    {'parent': 'discovery', 'node': 'delete_discovery'},
    {'parent': 'list', 'node': 'edit_discovery_activity'},
    {'parent': 'list', 'node': 'add_push'},
    {'parent': 'push', 'node': 'edit_push'},
    {'parent': 'list', 'node': 'delete_discovery'},
    {'parent': 'list', 'node': 'edit_discovery'},
    {'parent': 'configure', 'node': 'category_add'},
    {'parent': 'configure', 'node': 'category_edit'},
    {'parent': 'configure', 'node': 'category_delete'},
  ];

  public hidedList = [];
  public currentItems = {
    expanded: '',
    title: '',
    children: ''
  };
  menuTrees = [];

  constructor(private menuService: MenuService, private _router: Router) {
    // this.menus = PAGES_MENU;
    /*setInterval(() => {
     console.log('aaa');
     console.log(this.menuService.menus);
     }, 1000);*/
  }

  ngAfterViewInit() {
    /*this.menus = this.menuService.menus;
     console.log(this.menuService.menus);
     console.log('存在');
     this.updateMenu(this._router.url);*/
    // console.log(this.menus);
  }

  ngOnInit() {
    this.menuTree();
    // rel
    // if (!this.menuService.menus) {
    //   this.menuService.eventbus.subscribe(_event => {
    //       if (_event.type === 2) {
    //         this.menuService.updateMenu(_event.url);
    //         this.menus = _event.url;
    //         this.updateMenu(this._router.url);
    //         this.menuService.eventbus.emit({
    //           type: 1,
    //           url: this._router.url
    //         });
    //       }
    //     }
    //   );
    // } else {
    //   this.menus = this.menuService.menus;
    //   this.updateMenu(this._router.url);
    // }


    /*this.menus = PAGES_MENU;
     this.updateMenu(this.menus);*/


    /*if (!this.menuService.menus) {
     this.menuService.getMenu().subscribe(res => {
     this.menuService.updateMenu(res.data);
     console.log(res.data);
     this.menus = this.menuService.menus;
     this.updateMenu(this._router.url);
     this.menuService.eventbus.emit({
     type: 1,
     url: this._router.url
     });
     });
     console.log('加载');
     } else {
     this.menus = this.menuService.menus;
     console.log('存在');
     this.updateMenu(this._router.url);
     }*/

    /*this.menus = this.menuService.menus;
     console.log(this.menuService.menus);
     this.updateMenu(this._router.url);*/


    // console.log(this.menus);
    // console.log(this.menuService.menus);

    // this.menuItems = this.menuService.menuItems;
    // this._router.isActive()
    // this.updateMenu(this._router.url);
    // this.toggleChildren(this._router.url);
    // console.log('this.currentItems');
    // console.log(this.currentItems);
  }

  menuTree() {
    this.menuService.getMenu().subscribe(res => {
      if (res.code === 200) {
        this.menuTrees = res.data.children;
        this.renderMenuTree(this.menuTrees);
      }
    })
  }

  innerMenus = this.menus[0];

  public checkCount = 0;

  public renderMenuTree(arr, children?, parentAction?) {
    arr.map((e, i) => {
      if (children) {
        let flag = true;
        this.hideList.map((e1, i) => {
          if (parentAction == e1['parent'] && e['action'] == e1['node']) {
            flag = false;
            this.hidedList.push(e1);
          }
        });
        if (flag) {
          children.push({
            path: e.action,
            title: e.permission_name,
            children: []
          });
        }
      } else {
        if(this.innerMenus.length === 0) {
          this.innerMenus.push({
            path: e.action,
            title: e.permission_name,
            selected: 'true',
            expanded: 'true',
            sort: 100,
            children: []
          });
        } else {
          this.innerMenus.push({
            path: e.action,
            title: e.permission_name,
            selected: 'false',
            expanded: 'true',
            sort: 100,
            children: []
          });
        }
      }
      if (e.children) {
        let childrenNode = this.innerMenus[this.innerMenus.length - 1]['children'];
        this.renderMenuTree(e.children, childrenNode, e.action);
      } else {
        // if(this.menus[0].length > 0) {
        //   window.localStorage.setItem('sideTree',JSON.stringify(this.menus));
        // }
        if(this.menus[0].length > 0) {
          if(this.checkCount == 0) {
            this.checkCount++;
            let parentPath = this.menus[0][0]['path'];
            let nodePath = this.menus[0][0]['children'][0]['path'];
            this.currentItems = this.menus[0][0];
            this._router.navigate([parentPath + '/' + nodePath]);
          }
        }
        window.localStorage.setItem('sideTree', JSON.stringify(this.menus));
        window.localStorage.setItem('hidedList', JSON.stringify(this.hidedList));
      }
    });
  }

  // path: 'tuike/permissions',
  // title: '管理设置',
  // icon: '',
  // selected: 'false',
  // expanded: 'true',
  // sort: 100,


  public toggle(path: string) {
    this.updateMenu(path);
  }

  public toggleChildren(path: string) {
    const arrUrl = path.split('/');
    console.log(arrUrl);

    this.menus.forEach((items) => {
      items.forEach((item) => {
        if (arrUrl[1] + '/' + arrUrl[2] === item.path) {
          item.children.forEach((ite) => {
            if (arrUrl[3] === ite.path) {

              if (ite.expanded === 'true') {
                ite.expanded = 'false';
              } else {
                ite.expanded = 'true';
              }


              // ite.data.menu.expanded = !(ite.data.menu.expanded);
              // ite.data.menu.selected = !(ite.data.menu.selected);
            }
          });
          this.currentItems = item;
          console.log(this.currentItems);
          /*item.data.menu.expanded = true;
           item.data.menu.selected = true;
           this.currentItems = item;*/
        }
      });
    });

    // console.log(this.menus);


  }

  public updateMenu(path: string) {
    const arrUrl = path.split('/');
    this.menus.forEach((value) => {
      // 广告＼营销

      value.forEach((value1) => {
        value1.selected = 'false';
        if (arrUrl[1] + '/' + arrUrl[2] === value1.path) {
          value1.selected = 'true';
          this.currentItems = value1;
          // console.log('currentItems',this.currentItems);
          if (value1.expanded === 'false') {
            this._router.navigate([path]);
          }
          this._router.navigate([`${value1.path}/${this.currentItems.children[0]['path']}`]);

          value1.children.forEach((value2) => {
            if (arrUrl[3] === value2.path) {
              value2.expanded = 'true';
              if (value2.selected === 'true') {
                value2.selected = 'false';
              } else {
                value2.selected = 'true';
              }
            }
          });
        }
      });
    });

    console.log(this.currentItems);

    /*this.menuItems.forEach((items) => {
     if (!items) {
     return;
     }
     items.forEach((item) => {
     // item.data.menu.expanded = false;
     item.data.menu.selected = false;
     if (arrUrl[1] === item.path) {
     // item.data.menu.expanded = true;
     item.data.menu.selected = true;
     this.currentItems = item;
     if (item.data.menu.expanded === false) {
     this._router.navigate([path]);
     }
     if (!item.children) {
     return;
     }
     item.children.forEach((ite) => {
     if (arrUrl[2] === ite.path) {
     ite.data.menu.expanded = true;
     ite.data.menu.selected = !(ite.data.menu.selected);
     }
     });

     }
     });
     });*/
  }
}
